package com.htdata.iiot.tools;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.lang3.StringUtils;


public class UsrInfoParser {
	public static String HELP = "help";
	public static String KEY = "key";
	public static String INFO = "info";

	public static void usage(Options options) {
		HelpFormatter helpFormatter = new HelpFormatter();
		helpFormatter.setOptionComparator(null);
		helpFormatter.setWidth(120);
		
		//options with null caused exception, have to use sysout function
		//helpFormatter.printHelp("./zkConfig -z <ip:port> -e <filename> [-p <zkpath>]", null);
		System.out.print(helpFormatter.getSyntaxPrefix());
		System.out.println("./usrInfoParser [-k <DesKey>] -i <InfoText>");
		
		String prefix = StringUtils.repeat(" ", helpFormatter.getSyntaxPrefix().length());
		helpFormatter.setSyntaxPrefix(prefix);
		helpFormatter.printHelp("./usrInfoParser [-k <DesKey>] -i <InfoText>", options);
	}

	public static void main(String[] args) {
		String desKey = null;
		String usrInfo = null;
		String srcText = null;
		
		Options optionsH = new Options();
		optionsH.addOption("h", UsrInfoParser.HELP, false, "show help information");

		Options options = new Options();
		options.addRequiredOption("i", UsrInfoParser.INFO, true, "info parameter in url");
		options.addOption("k", UsrInfoParser.KEY, true, "des key");

		if (args.length == 0) {
			usage(options);
			return;
		}

		CommandLine commandLine = null;
		CommandLineParser parser = null;
		parser = new DefaultParser();

		try {
			commandLine = parser.parse(optionsH, args);
			if (commandLine.hasOption('h')) {
				usage(options);
				return;
			}
		} catch (Exception e) {
		}

		try {
			commandLine = parser.parse(options, args);
			desKey = commandLine.getOptionValue(UsrInfoParser.KEY);
			usrInfo = commandLine.getOptionValue(UsrInfoParser.INFO);

			if(desKey != null && !desKey.isEmpty()){
				srcText = SecurityHelper.decrypt(usrInfo, desKey);
			} else {
				srcText = SecurityHelper.decrypt(usrInfo);
			}
			
			System.out.println(srcText);
		} catch (Exception e) {
			usage(options);
			return;
		}
	}

}
